package com.chaoyong.higo.utils;


import java.util.List;

import android.app.Activity;
import android.os.Handler;
import android.os.Looper;
import android.view.KeyEvent;
import android.widget.Toast;

import com.chaoyong.higo.R;
import com.chaoyong.higo.cainiaowo.CartProvider;
import com.chaoyong.higo.cainiaowo.ShoppingCart;
import com.nostra13.universalimageloader.core.ImageLoader;

/**
 * Created by Administrator on 2015/12/3.
 */
public class DoubleClickExitHelper {
    private final Activity mActivity;

    private boolean isOnKeyBacking;
    private Handler mHandler;
    private Toast mBackToast;

    public DoubleClickExitHelper(Activity activity) {
        mActivity = activity;
        mHandler = new Handler(Looper.getMainLooper());
    }

    /**
     * Activity onKeyDown浜嬩欢
     * */
    public boolean onKeyDown(int keyCode, KeyEvent event,Activity act) {
        if(keyCode != KeyEvent.KEYCODE_BACK) {
            return false;
        }
        if(isOnKeyBacking) {
            mHandler.removeCallbacks(onBackTimeRunnable);
            if(mBackToast != null){
                mBackToast.cancel();
            }
            
            /**
             * 退出程序就把购物车清空，ios就是这么处理的
             */
            CartProvider cp = new CartProvider(act);
            List<ShoppingCart> carts = cp.getAll();
            if(carts.size() != 0){
            	for (int i = 0; i < carts.size(); i++) {
            		cp.delete(carts.get(i));
            	}
            }
            //----end----
            
            AtyManager.getAtyManager().finishAllActivity();

            ImageLoader.getInstance().clearDiscCache();
            ImageLoader.getInstance().clearMemoryCache();

            // 閫�嚭
            AtyManager.getAtyManager().appExit(mActivity);
            return true;
        } else {
            isOnKeyBacking = true;
            if(mBackToast == null) {
                mBackToast = Toast.makeText(mActivity, "再按一次退出" + mActivity.getResources().getString(R.string.app_name), Toast.LENGTH_SHORT);
            }
            mBackToast.show();
            mHandler.postDelayed(onBackTimeRunnable, 2000);
            return true;
        }
    }

    private Runnable onBackTimeRunnable = new Runnable() {

        @Override
        public void run() {
            isOnKeyBacking = false;
            if(mBackToast != null){
                mBackToast.cancel();
            }
        }
    };
}
